import React, { Component } from 'react';
import { Button, Form, Input, Radio, Space, Modal, Select } from "antd";
import { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import TheUpload from "@/components/TheUpload";
import { apiActivityLinkList } from "@/request/h5"
import TheQuill from "@/components/TheQuill";
import Search from 'antd/lib/transfer/search';
import List from './carousellist'
import { urlReg } from '@/utils/regexp.js'
const { Option } = Select
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
class Editor extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visibleHome: false,
            configCarouselUriApplet: "",
            iconFileList: null,
            fileList: null,
            radioValue: '',
            visible: false,
            configCarouselUri: '',
            category: '',
            configCarouselSite: "",
            arr: [],
            activeList: [],
            initialValues: {
                configCarouselType: '',
                newMemberShow: '0',
            },
            newMemberValue: '0',
        }
    }

  componentDidMount() {
    this.getActiveList()
    if (this.props.configCarouselSite) {
      this.setState({ configCarouselSite: this.props.configCarouselSite })
    } else {
      this.setState({ configCarouselSite: "" })
    };
    if (this.props.category === "button") {
      this.setState({

            })
        }
        if (this.props.type === 'editor') {
            let value = { ...this.props.data }
            if (value.configCarouselType !== '1') {
                if (value.configCarouselUri !== '') {
                    this.setState({
                        configCarouselUri: value.configCarouselUri,
                    })
                }
                if (value.configCarouselUriApplet !== '') {
                    this.setState({
                        configCarouselUriApplet:value.configCarouselUriApplet,
                    })
                }
            } else {
                let users = []
                let url = []
                if (value.configCarouselUri.indexOf('?') != '-1') {
                    url = value.configCarouselUri.split('?')
                    value.configCarouselUri = url[0]
                    users = url[1].split('&')
                    let str = ''
                    users.map((item) => {
                        str = item.split('=')
                        this.state.arr.push({
                            key: str[0],
                            value: str[1]
                        })
                    })
                } else {
                    value.configCarouselUri = value.configCarouselUri.trim()
                }
            }
            this.formRef.setFieldsValue({ ...value })
            const fileList = [
                {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: value.configCarouselFilez,
                },
            ];
            let iconFileList = []
            if (value.icon) {
                iconFileList = [
                    {
                        uid: '-1',
                        name: 'image.png',
                        status: 'done',
                        url: value.icon,
                    },
                ];
            }
            this.setState({
                fileList,
                iconFileList,
                radioValue: value.configCarouselType,
                btnLoading: value.btnLoading,
                dialogCancel: value.dialogCancel,
                configCarouselUri: value.configCarouselUri
                // configCarouselContent: this.props.data.configCarouselContent || ' '
            }, () => {
                // console.log(this.state, 'ssss')
            })
        }

  }

  /**
   * @desc 获取图片Id插入到form表单中
   * @param data
   */
  getFileResult = data => {
    if (data && data.length > 0) {
      let str = data.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        } else {
          return ''
        }
      }).join(',')

            this.formRef.setFieldsValue({ configCarouselFilez: str })
        } else {
            this.formRef.setFieldsValue({ configCarouselFilez: '' })
        }
    }
    getFileResultIcon = data => {
        if (data && data.length > 0) {
            let str = data.map(v => {
                if (v.response && v.response.code === 0) {
                    return v.response.data
                } else {
                    return ''
                }
            }).join(',')
            this.formRef.setFieldsValue({ icon: str })
            console.log(this.formRef.getFieldValue('icon'));
        } else {
            this.formRef.setFieldsValue({ icon: '' })
        }
    }
    radioChange = (e) => {
        this.setState({
            configCarouselUri: ''
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: '', users: '' })
            const CarouselType = e.target.value
            if (CarouselType !== '1') {
                this.openMadol(CarouselType)
            } else {
                this.setState({
                    configCarouselUri: '',
                    users: ''
                })
            }
            this.setState({
                radioValue: e.target.value,
            })
        })
    }
    chooseWechatPath = () => {
        e:
        this.setState({
            visibleHome: true,
            typetitle: '上门服务'
        })
    }
    openMadol = (CarouselType) => {
        switch (CarouselType) {
            case '2':
                this.setState({
                    visible: true,
                    typetitle: '商城门店'
                })
                break;
            case '3':
                this.setState({
                    visible: true,
                    typetitle: '商城商品'
                })
                break;
            case '4':
                this.setState({
                    visible: true,
                    typetitle: '线下门店'
                })
                break;
            case '5':
                this.setState({
                    visible: true,
                    typetitle: '线下商品'
                })
                break;
            case '6':
                this.setState({
                    visible: true,
                    typetitle: '服务'
                })
                break;
            case '9':
                this.setState({
                    visible: true,
                    typetitle: '服务类目'
                })
                break;
            case '14':
                this.setState({
                    visible: true,
                    typetitle: '宠物酒店'
                })
                break;
            case '15':
                this.setState({
                    visible: true,
                    typetitle: '宠物医院'
                })
                break;
            case '16':
                this.setState({
                    visible: true,
                    typetitle: '洗护美容'
                })
                break;
            case '28':
                this.setState({
                    visible: true,
                    typetitle: '上门服务'
                })
                break;
            case 'uniapp-service':
                this.setState({
                    visible: true,
                    typetitle: '上门服务'
                })
                break;
            default:
                break;
        }
    }
    // 外链地址下拉内容
    async getActiveList() {
        await apiActivityLinkList().then(res => {
            if (res.code === 0) {
                this.setState({
                    activeList: res.data
                })
            }
        })
    }
    onHomeCancel = () => {
        this.setState({
            configCarouselUriApplet:'',
            visibleHome: false
        })
    }
    onCancel = () => {
        this.setState({
            visible: false
        })
    }
    onOk = (e) => {
        this.setState({
            visible: false
        })
    }
    onFinish = (value) => {
        if (this.state.radioValue !== '1') {
            value.configCarouselUri = this.state.configCarouselUri
            value.configCarouselUriApplet = this.state.configCarouselUriApplet
            value.icon = this.formRef.getFieldValue('icon')
        } else {
            value.configCarouselUri = value.configCarouselUri.trim()
        }
        let str = ''
        if (value.users && value.users.length !== 0) {
            value.users.map((item, index) => {
                str += item.key + '=' + item.value
                if (index + 1 !== value.users.length) {
                    str += '&'
                }
            })
            value.configCarouselUri = value.configCarouselUri.trim() + '?' + str
            delete value.users
        } else {
            value.configCarouselUri = value.configCarouselUri.trim()
            value.configCarouselUriApplet = value.configCarouselUriApplet
        }

        this.props.onFinish(value)
    }
    goDetail(param) {
        let { type, typeId, typeName, storeId, storeName } = param;
        switch (type) {
            case '2':
                const mallobj = { storeId: typeId, storeName: typeName }
                const mallCarouselUri = JSON.stringify(mallobj);
                this.setState({
                    visible: false,
                    configCarouselUri: mallCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: typeName })
                })
                break;
            case '3':
                const goodsobj = { goodsId: typeId, goodsName: typeName, storeId: storeId, storeName: storeName }
                const goodsCarouselUri = JSON.stringify(goodsobj);
                this.setState({
                    visible: false,
                    configCarouselUri: goodsCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
                })
                break;

            case '4':
                const storeobj = { storeId: typeId, storeName: typeName }
                const storeCarouselUri = JSON.stringify(storeobj);
                this.setState({
                    visible: false,
                    configCarouselUri: storeCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: typeName })
                })
                break;
            case '14':
                const hotelobj = { storeId: typeId, storeName: typeName, type: 'HOTEL' }
                const hotelUri = JSON.stringify(hotelobj);
                this.setState({
                    visible: false,
                    configCarouselUri: hotelUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: typeName })
                })
                break;
            case '15':
                const hospitalobj = { storeId: typeId, storeName: typeName, type: 'HOSPITAL' }
                const hospitalUri = JSON.stringify(hospitalobj);
                this.setState({
                    visible: false,
                    configCarouselUri: hospitalUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: typeName })
                })
                break;
            case '16':
                const hairdressobj = { storeId: typeId, storeName: typeName, type: "HAIRDRESSING" }
                const hairdressUri = JSON.stringify(hairdressobj);
                this.setState({
                    visible: false,
                    configCarouselUri: hairdressUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: typeName })
                })
                break;
            case '28':
                const UPDOORobj = { storeId: typeId, storeName: typeName, type: "UPDOOR" }
                const UPDOORUri = JSON.stringify(UPDOORobj);
                this.setState({
                    visible: false,
                    configCarouselUri: UPDOORUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: typeName })
                })
                break;
            case 'uniapp-service':
                const uniappServiceRobj = { storeId: typeId, storeName: typeName, type: "UPDOOR" }
                const uniappServiceRUri = JSON.stringify(uniappServiceRobj);
                this.setState({
                    visible: false,
                    configCarouselUriApplet: uniappServiceRUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUriApplet: typeName })
                })
                break;
            case '5':
                const productobj = { productId: typeId, productName: typeName, storeId: storeId, storeName: storeName }
                const productCarouselUri = JSON.stringify(productobj);
                this.setState({
                    visible: false,
                    configCarouselUri: productCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
                })
                break;
            case '6':
                const serviceobj = { serviceId: typeId, serviceName: typeName, storeId: storeId, storeName: storeName }
                const serviceCarouselUri = JSON.stringify(serviceobj);
                this.setState({
                    visible: false,
                    configCarouselUri: serviceCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
                })
                break;
            case '9':
                const categoryobj = { serviceClassifyId: typeId, serviceClassifyName: typeName, }
                const serviceCategorylUri = JSON.stringify(categoryobj);
                this.setState({
                    visible: false,
                    configCarouselUri: serviceCategorylUri
                }, () => {
                    this.formRef.setFieldsValue({ configCarouselUri: `${typeName}` })
                })
                break;
            default:
                break;
        }
    }
    goDetailHome(param) {
        let { type, typeId, typeName, storeId, storeName } = param;
        const uniappServiceRobj = { storeId: typeId, storeName: typeName, type: "UPDOOR",path:"/pages/callOut/index" }
        const uniappServiceUri = JSON.stringify(uniappServiceRobj);
        this.setState({
            visibleHome: false,
            configCarouselUriApplet: uniappServiceUri
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUriApplet: typeName })
        })
    }
    newMemberChange = (e) => {
        this.formRef.setFieldsValue({ newMemberValue: e.target.value })
        this.setState({
            newMemberValue: e.target.value,
        })
    }
    configCarouselUriChange = (e) => {
        this.formRef.setFieldsValue({ users: '' })
        this.setState({
            configCarouselUri: e
        })
    }
    getStringName(carouselUri, type) {
        let str = ''
        if (type !== '1') {
            if (carouselUri !== '') {
                carouselUri = JSON.parse(carouselUri)
                switch (type) {
                    case '2':
                        str = carouselUri.storeName
                        break;
                    case '3':
                        str = carouselUri.goodsName + carouselUri.storeName
                        break;
                    case '4': case '14': case '15': case '16':
                        str = carouselUri.storeName
                        break;
                    case '5':
                        str = carouselUri.productName + carouselUri.storeName
                        break;
                    case '6':
                        str = carouselUri.serviceName + carouselUri.storeName
                        break;
                    case '7':
                        str = ''
                        break;
                    case '8':
                        str = ''
                        break;
                    case '9':
                        str = carouselUri.serviceClassifyName
                        break;
                    case '10':
                        str = ''
                        break;
                    case '11':
                        str = ''
                        break;
                    case "12":
                        str = ""
                        break;
                    case "13":
                        str = ""
                        break;
                    case '28':
                        str = carouselUri.storeName
                        break;
                    default:
                        break;
                }
            }
        }
        return str
    }
    getJson = (params) => {
        let str = ''
        if (params) {
            str = JSON.parse(params).storeName
        }
        return str
    }

    render() {
        const { btnLoading, visibleHome, radioValue, visible, typetitle, configCarouselUri, configCarouselUriApplet, initialValues, category, configCarouselSite, newMemberValue, arr, activeList } = this.state
        const { data, dialogCancel } = this.props
        return (
            <Form
                ref={(ref) => {
                    this.formRef = ref;
                }}
                {...formItemLayout}
                labelWrap
                onFinish={this.onFinish}
                initialValues={initialValues}
            >
                <Form.Item rules={[{ required: true, message: '请输入标题' }]} name={'configCarouselTitle'} label={'标题'}>
                    <Input maxLength={20} />
                </Form.Item>
                <Form.Item rules={[{ required: true, message: '请选择图片' }]} name={'configCarouselFilez'} label={'图片'}>
                    {this.props.data && this.state.fileList && this.state.fileList.length &&
                        <TheUpload isConversion={false} maxSize={10} fileList={this.state.fileList} data={{ attachKey: '1' }} len={1}
                            getFileResult={this.getFileResult} />}
                    {
                        !this.props.data && <TheUpload isConversion={false} maxSize={10} data={{ attachKey: '1' }} len={1}
                            getFileResult={this.getFileResult} />
                    }
                </Form.Item>
                <Form.Item rules={[{ message: '请选择图片' }]} name={'icon'} label={'角标'}>
                    {this.props.data && this.state.iconFileList &&
                        <TheUpload isConversion={false} maxSize={1} accept={["image/png", "image/gif"]} fileList={this.state.iconFileList} data={{ attachKey: '1' }} len={1}
                            getFileResult={this.getFileResultIcon} />}
                    {
                        !this.props.data && <TheUpload isConversion={false} accept={["image/png", "image/gif"]} maxSize={1} data={{ attachKey: '1' }} len={1}
                            getFileResult={this.getFileResultIcon} />
                    }
                </Form.Item>
                <Form.Item rules={[{ required: true, message: '请选择' }]} name={'newMemberShow'} label={'是否只对新人展示'} >
                    <Radio.Group defaultValue={newMemberValue} >
                        <Radio onClick={(e) => this.newMemberChange(e)} value={'1'}>是</Radio>
                        <Radio onClick={(e) => this.newMemberChange(e)} value={'0'}>否</Radio>
                    </Radio.Group>
                </Form.Item>
                {
                    category === "1" ? <Form.Item rules={[{ required: false, message: '请输入位置排序' }, {
                        pattern: /^[0-9]*$/,
                        message: '必须填写正整数'
                    }]} name={'configCarouselSort'} label={'位置排序'} hidden>
                        <Input readOnly />
                    </Form.Item> : <Form.Item rules={[{ required: true, message: '请输入位置排序' }, {
                        pattern: /^[0-9]*$/,
                        message: '必须填写正整数'
                    }]} name={'configCarouselSort'} label={'位置排序'}>
                        <Input maxLength={5} placeholder="*App展示顺序由小到大,相同排序按添加先后顺序展示" />
                    </Form.Item>
                }

                <Form.Item rules={[{ required: true, message: '请选择外链' }]} name={'configCarouselType'} label={'外链'}>
                    <Radio.Group onChange={this.radioChange} initialValue={radioValue} buttonStyle="solid" optionType='button' >
                        <Radio onClick={this.radioChange} value={'1'}>地址链接</Radio>
                        {/* <Radio onClick={this.radioChange} value={'2'}>商城门店</Radio> */}
                        <Radio onClick={this.radioChange} value={'3'}>商城商品</Radio>
                        <Radio onClick={this.radioChange} value={'4'}>线下门店</Radio>
                        <Radio onClick={this.radioChange} value={'5'}>线下商品</Radio>
                        {/* <Radio onClick={this.radioChange} value={'6'}>服务</Radio> */}
                        <Radio onClick={this.radioChange} value={'7'}>邀请有礼</Radio>
                        <Radio onClick={this.radioChange} value={'8'}>砍一刀</Radio>
                        {/* <Radio onClick={this.radioChange} value={'9'}>服务列表</Radio> */}
                        <Radio onClick={this.radioChange} value={'10'}>我的卡包</Radio>
                        <Radio onClick={this.radioChange} value={'11'}>宠物出行</Radio>
                        {configCarouselSite === "3" || configCarouselSite === "4" ? <Radio onClick={this.radioChange} value={'12'}>正品保障</Radio> : ""}
                        <Radio onClick={this.radioChange} value={'13'}>宠物打车</Radio>
                        <Radio onClick={this.radioChange} value={'14'}>宠物酒店</Radio>
                        <Radio onClick={this.radioChange} value={'15'}>宠物医院</Radio>
                        <Radio onClick={this.radioChange} value={'16'}>洗护美容</Radio>
                        <Radio onClick={this.radioChange} value={'20'}>领券中心</Radio>
                        <Radio onClick={this.radioChange} value={'21'}>全部分类</Radio>
                        <Radio onClick={this.radioChange} value={'22'}>全网好货</Radio>
                        <Radio onClick={this.radioChange} value={'23'}>商城首页</Radio>
                        <Radio onClick={this.radioChange} value={'24'}>拼团频道</Radio>
                        <Radio onClick={this.radioChange} value={'26'}>秒杀频道</Radio>
                        <Radio onClick={this.radioChange} value={'27'}>签到积分</Radio>
                        <Radio onClick={this.radioChange} value={'28'}>上门服务</Radio>
                        <Radio onClick={this.radioChange} value={'29'}>上门服务新</Radio>
                        <Radio onClick={this.radioChange} value={'30'}>幸运抽奖</Radio>
                        <Radio onClick={this.radioChange} value={'32'}>宠圈首页</Radio>
                        <Radio onClick={this.radioChange} value={'33'}>宠物翻译</Radio>
                        <Radio onClick={this.radioChange} value={'34'}>免费问诊</Radio>
                        <Radio onClick={this.radioChange} value={'35'}>宠物定位</Radio>
                        {/* <Radio onClick={this.radioChange} value={'36'}>官方群列表</Radio> */}
                    </Radio.Group>
                </Form.Item>
                {radioValue === '' ? <Form.Item
                    // rules={[{ required: true, message: '请输入地址链接' }, {
                    //     // pattern: urlReg,
                    //     message: '请输入正确的链接地址'
                    //
                    // }]}
                    name={'configCarouselUri'}
                    label={'选择链接(APP)'}
                >
                    <Input />
                </Form.Item> :
                    (["7", "8", "10", "11", "12", "13", "20", "21", "22", "23", "24", "26", "27", "29", "30", "32", '33', '34', '35', '36'].includes(radioValue)) ?
                        <Form.Item name={'configCarouselUri'}
                            label={'选择链接(APP)'}>
                            <Input readOnly placeholder="无需填写" />
                        </Form.Item> :
                        <Form.Item name={'configCarouselUri'}
                            label={'选择链接(APP)'}
                            rules={[{ required: radioValue !== '1' ? true : false, message: '请选择链接' }]}>
                            {radioValue === '1' ? <Select onChange={this.configCarouselUriChange}>
                                {
                                    activeList.map(item => <Option value={item.activityLink} key={item.id}>{item.activityName}</Option>)
                                }
                            </Select> : <div style={{ border: '1px solid #ccc', lineHeight: '28px', paddingLeft: '10px', minHeight: '30px' }}>
                                {
                                    this.getStringName(configCarouselUri, radioValue)
                                }
                            </div>}
                        </Form.Item>
                }
                {
                    radioValue === '1' && configCarouselUri !== '' ? <Form.List name="users" initialValue={arr}>
                        {(fields, { add, remove }) => (
                            <>
                                <Form.Item label="参数">
                                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                        添加参数
                                    </Button>
                                </Form.Item>
                                {fields.map(({ key, name, ...restField }) => (
                                    <Form.Item
                                        {...formItemLayoutWithOutLabel}
                                        required={false}
                                        key={key}
                                        style={{
                                            margin: 0
                                        }}
                                    >
                                        <Space
                                            style={{
                                                display: 'flex',
                                                marginBottom: 0,
                                            }}
                                            align="baseline"
                                        >
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'key']}
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请输入参数名',
                                                    },
                                                ]}

                      >
                        <Input placeholder="参数名" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        rules={[
                          {
                            required: true,
                            message: '请输入参数值',
                          },
                        ]}
                      >
                        <Input placeholder="参数值" />
                      </Form.Item>
                      <CloseCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  </Form.Item>
                ))}

                            </>
                        )}
                    </Form.List> : ''
                }
                {['28'].includes(radioValue) && <Form.Item name={'configCarouselUriApplet'}
                    label={'选择链接(小程序)'}
                >
                    <div style={{ border: '1px solid #ccc', lineHeight: '28px', paddingLeft: '10px', minHeight: '30px' }} onClick={this.chooseWechatPath}>
                        {
                            this.getJson(configCarouselUriApplet)
                        }
                    </div>
                </Form.Item>}
                <Modal
                    visible={visibleHome}
                    onCancel={this.onHomeCancel}
                    title={typetitle}
                    width='1000px'
                    destroyOnClose={true}
                    footer={null}
                >
                    <List radiotype={'uniapp-service'} getList={(e) => this.goDetailHome(e)} />
                </Modal>
                <Modal
                    visible={visible}
                    onCancel={this.onCancel}
                    title={typetitle}
                    width='1000px'
                    destroyOnClose={true}
                    footer={null}
                >
                    <List radiotype={radioValue} getList={(e) => this.goDetail(e)} />
                </Modal>
                <div className="p-text-align">
                    <Space size="large">
                        <Button key="back" onClick={dialogCancel}>
                            取 消
                        </Button>
                        <Button type="primary" loading={btnLoading} htmlType="primary">
                            确 定
                        </Button>
                    </Space>
                </div>
            </Form>
        );
    }
}

export default Editor;
